﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using RT = Coolzon.Metadata.Runtime;

namespace Coolzon.UI.Core.Converters
{
    /// <summary>
    /// 画刷转换器
    /// </summary>
    public class BrushConverter : ValueConverter
    {
        public object Convert(ConvertContext context, RT.Property property)
        {
            if (!string.IsNullOrEmpty(property.ValueString))
            {
                object colorObj = null;
                if (property.ValueString.Contains(".") == false)
                {
                    try
                    {
                        colorObj = ColorConverter.ConvertFromString(property.ValueString);
                    }
                    catch (Exception ex)
                    {

                    }
                }
                if (colorObj == null)
                {
                    // maybe this is a image path
                    string imageFilepath = Path.Combine(context.SolutionDirectory, property.ValueString);
                    return new ImageBrush(new BitmapImage(new Uri(imageFilepath)));
                }
                else
                {
                    return new SolidColorBrush((Color)colorObj);
                }
            }
            else
            {
                return ConvertFromValueNode(context, property.ValueNode);
            }
        }

        public RT.ValueNode ConvertBack(ConvertContext context, object value, object dtTagData)
        {
            if(value == null)
            {
                return null;
            }
            RT.ValueNode vNode = null;
            Brush brush = value as Brush;
            if (brush is SolidColorBrush)
            {
                vNode = new RT.ValueNode("SolidBrush");
                vNode.Attributes = new Dictionary<string, string>();
                Color color = (Color)ColorConverter.ConvertFromString(System.Convert.ToString(brush));
                string colorString = color.ToString();
                vNode.Attributes.Add("Color", colorString);
            }
            else if (brush is ImageBrush)
            {
                vNode = new RT.ValueNode("ImageBrush");
                vNode.Attributes = new Dictionary<string, string>();
                ImageBrush imageBrush = (ImageBrush)brush;
                string imagePath = "";
                vNode.Attributes.Add("Source", imagePath.Replace("/", "\\").Replace(context.SolutionDirectory, ".\\"));
                vNode.Attributes.Add("TileMode", imageBrush.TileMode.ToString());
                vNode.Attributes.Add("Stretch", imageBrush.Stretch.ToString());
            }
            else if (brush is LinearGradientBrush)
            {
                vNode = new RT.ValueNode("LinearGradientBrush");
                vNode.Attributes = new Dictionary<string, string>();
                LinearGradientBrush linearGradientBrush = (LinearGradientBrush)brush;
                vNode.Attributes.Add("StartPoint", linearGradientBrush.StartPoint.ToString());
                vNode.Attributes.Add("EndPoint", linearGradientBrush.EndPoint.ToString());

                foreach (GradientStop gs in linearGradientBrush.GradientStops)
                {
                    RT.ValueNode vGs = new RT.ValueNode("GradientStop");
                    vGs.Attributes = new Dictionary<string, string>();
                    vGs.Attributes.Add("Color", gs.Color.ToString());
                    vGs.Attributes.Add("Offset", gs.Offset.ToString());

                    if (vNode.ValueNodes == null)
                        vNode.ValueNodes = new List<RT.ValueNode>();
                    vNode.ValueNodes.Add(vGs);
                }
            }
            return vNode;
        }

        public static Brush ConvertFromValueNode(ConvertContext context, RT.ValueNode valueNode)
        {
            if (valueNode.Name.Equals("SolidColorBrush"))
            {
                string colorString = valueNode.Attributes["Color"];
                if (!string.IsNullOrEmpty(colorString))
                {
                    SolidColorBrush scb = new SolidColorBrush((Color)ColorConverter.ConvertFromString(colorString));
                    return scb;
                }
            }
            else if (valueNode.Name.Equals("ImageBrush"))
            {
                string stretchString = valueNode.GetAtrributeValue("Stretch");
                string sourceString = valueNode.GetAtrributeValue("ImageSource");
                if (!string.IsNullOrEmpty(sourceString))
                {
                    sourceString = Path.Combine(context.SolutionDirectory, sourceString);
                    ImageBrush scb = new ImageBrush(new BitmapImage(new Uri(sourceString)));
                    Stretch stretch;
                    if (!Enum.TryParse<Stretch>(stretchString, out stretch))
                    {
                        stretch = Stretch.Fill;
                    }
                    scb.Stretch = stretch;
                    return scb;
                }
            }
            else if (valueNode.Name.Equals("LinearGradientBrush"))
            {
                LinearGradientBrush lgb = new LinearGradientBrush();


                string strStartPoint = valueNode.Attributes["StartPoint"];
                string strEndPoint = valueNode.Attributes["EndPoint"];
                if (!string.IsNullOrEmpty(strStartPoint) && !string.IsNullOrEmpty(strEndPoint))
                {
                    string[] startPoints = strStartPoint.Split(',');
                    string[] endPoints = strEndPoint.Split(',');

                    lgb.StartPoint = new System.Windows.Point(double.Parse(startPoints[0]), double.Parse(startPoints[1]));
                    lgb.EndPoint = new System.Windows.Point(double.Parse(endPoints[0]), double.Parse(endPoints[1]));
                }

                foreach (RT.ValueNode vN in valueNode.ValueNodes)
                {
                    if (!string.IsNullOrEmpty(vN.Attributes["Color"]))
                    {
                        double offset = 0.0;
                        if (vN.Attributes.ContainsKey("Offset"))
                        {
                            double.TryParse(vN.Attributes["Offset"], out offset);
                        }

                        GradientStop gs = new GradientStop((Color)ColorConverter.ConvertFromString(vN.Attributes["Color"]), offset);
                        lgb.GradientStops.Add(gs);
                    }
                }
                return lgb;
            }
            return null;
        }
    }
}
